/* eslint-disable space-before-function-paren */
/* eslint-disable object-curly-spacing */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
// import getPageTitle from '@/utils/get-page-title';
import { findCodes, getFirstRoute } from "@/utils/utils";
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['/login', '/auth-redirect', '/401', '/404']; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();
  // set page title
  // determine whether the user has logged in
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' });
      NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0;
      if (hasRoles) {
        // 设置第一条权限路由
        // const routePath = getFirstRoute(store.getters.permission_routes, store.getters.permission_routes[0].path)
        // next({ path: routePath, replace: true, query: { noGoBack: true } });
        // 计算页面级别下具体操作权限
        let path = to.path.split('/').pop();
        if (to.path.endsWith('index')) {
          path = to.path;
        }
        // let codes = ['create', 'edit', 'query', 'search', 'delete', 'Query', 'Create', 'Delete', 'Edit'];
        let codes = findCodes(store.getters.permission_routes, path);
        store.commit('user/SET_CODES', codes);
        // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
        if (codes.length > 0 || path == '401' || path == '404' || path == 'dashboard') {
          next()
        } else {
          next({ path: '/401', replace: true, query: { noGoBack: true } });
        }
      } else {
        try {
          // get left menus
          await store.dispatch('user/getLeftMenus');
          // 设置第一条权限路由
          const routePath = getFirstRoute(store.getters.permission_routes, store.getters.permission_routes[0].path)
          next({ path: routePath, replace: true, query: { noGoBack: true } });
          // 计算页面级别下具体操作权限
          let path = to.path.split('/').pop();
          if (to.path.endsWith('index')) {
            path = to.path;
          }
          // let codes = ['create', 'edit', 'query', 'search', 'delete', 'Query', 'Create', 'Delete', 'Edit'];
          let codes = findCodes(store.getters.permission_routes, path);
          store.commit('user/SET_CODES', codes);
          // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
          if (codes.length > 0 || path == '401' || path == '404' || path == 'dashboard') {
            next()
          } else {
            next({ path: '/401', replace: true, query: { noGoBack: true } });
          }
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken');
          Message.error(error || '获取菜单失败, 请稍后再试');
          next(`/login`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

